<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
error_reporting(E_ERROR | E_PARSE );

function checkLogin () {
    global $_core;
    if($_core['member']) {
        echo 'login';
    }else{
        header('Location: /index/index/oauth');
        die();
    }
}

/*
 * 判断是否是微信内
 */
function isWeixin() { 
  if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) { 
    return true; 
  } else {
    return false; 
  }
}

/*
 * 打印数组,用于输出调试信息
 * @param array $arr
 */
function pr($arr) {
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
}

/*
 * 打印数组,并中断执行,用于输出调试信息
 */
function _pr($arr) {
    pr($arr);
    exit;
}

function getDateTime () {
    return date('Y-m-d H:i:s');
}

function getUserSign($uid) {
    $userModel = model('user');
    $userinfo = $userModel->where('uid',$uid)->find();
    if($userinfo['user_sign'] && time()>=$userinfo['user_sign_expire']){
        return $userinfo['user_sign'];
    }
    $command = '/www/tls_sig_api-linux-64/bin/signature'
            . ' ' . escapeshellarg('/www/tls_sig_api-linux-64/my/private_key')
            . ' ' . escapeshellarg('1400099653')
            . ' ' . escapeshellarg($userinfo['uniid']);
    $ret = exec($command, $out, $status);
    if ($status == -1) {
        return false;
    }
    $save = [
        'user_sign' => $out[0],
        'user_sign_expire' => time()+170*24*3600
    ];
    $userModel->where('uid',$uid)->update($save);
    return $out[0];
}

function ajaxReturn ($code,$msg,$data='') {
    return json(array(
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ));
}

function returnJson ($code,$msg,$data='',$url='') {
    return json(array(
        'ret' => $code,
        'message' => $msg,
        'data' => $data,
        'url'=>$url
    ));
}


function exitReturn ($code,$msg,$data) {
    $res = json(array(
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ));
    exit($res);
}

/*
 * 发送群消息
 */
function sendGroupMsg ($groupid,$arr) {
    vendor('timSdk/TimRestApi');
    $timCtl = new \TimRestAPI();
    $data = base64_encode(json_encode($arr));
    $timCtl->group_send_group_msg('hai105', $groupid, $data);
}

function sendMsg ($account,$arr) {
    vendor('timSdk/TimRestApi');
    $timCtl = new \TimRestAPI();
    $data = base64_encode(json_encode($arr));
    if(is_array($account)) {
        $res = $timCtl->openim_batch_sendmsg($account, $data);
    }else{
        $res = $timCtl->openim_send_msg(config('admin_account'), $account, $data);
    }
}

function deleteGroupMember ($groupid,$member_id) {
    vendor('timSdk/TimRestApi');
    $timCtl = new \TimRestAPI();
    $timCtl->group_delete_group_member($groupid, $member_id, 1);
}

function arraySort($arrays, $sort_key, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC) {
    if (is_array($arrays)) {
        foreach ($arrays as $array) {
            if (is_array($array)) {
                $key_arrays[] = $array[$sort_key];
            } else {
                return false;
            }
        }
    } else {
        return false;
    }
    array_multisort($key_arrays, $sort_order, $sort_type, $arrays);
    return $arrays;
}


/*
 * $log = [
 * uid => uid,
 * type => 1/2 1money 2cash
 * note=> 备注
 * money => 0
 * ]
 */
function core_moneylog ($log) {
    if($log['money']==0){
        return false;
    }
    $log['create_time'] = date('Y-m-d H:i:s');
    $field = $log['type']==1?'money':'cash';
    $log['logtype'] = $log['money']>0?1:0;
    $log['money'] = abs($log['money']);
    if($log['logtype']) {
        db('user')->where(['uid'=>$log['uid']])->setInc($field,$log['money']);
    }else{
        db('user')->where(['uid'=>$log['uid']])->setDec($field,$log['money']);
    }
    db('moneylog')->insert($log);
}

function core_uid2openid ($uid) {
    if(!is_numeric($uid)) {
        return $uid;
    }
    $user = db('user')->where('uid',$uid)->find();
    if($user) {
        return $user['openid']?$user['openid']:false;
    }
    return false;
}

function addlog($data) {
    if($data) {
        file_put_contents(ROOT_PATH . '/log.txt', 'error:' . $data . PHP_EOL, FILE_APPEND);
    }
    $get = json_encode($_GET, JSON_UNESCAPED_UNICODE);
    $input = json_encode(input());
    file_put_contents(ROOT_PATH . '/log.txt', PHP_EOL . 'time:' . date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
    file_put_contents(ROOT_PATH . '/log.txt', 'get:' . $get . PHP_EOL, FILE_APPEND);
    file_put_contents(ROOT_PATH . '/log.txt', 'input:' . $input . PHP_EOL, FILE_APPEND);
}

function _login ($uid) {
    $info = db('user')->where('uid',$uid)->find();
    session('userinfo',$info);
}


function http_get($url){
    $oCurl = curl_init();
    if(stripos($url,"https://")!==FALSE){
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if(intval($aStatus["http_code"])==200){
        return $sContent;
    }else{
        return false;
    }
}

function http_post($url,$params,$post_file=false){
    $oCurl = curl_init();
    if(stripos($url,"https://")!==FALSE){
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    if(is_array($params)) {
        $params = json_encode($params);
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($oCurl, CURLOPT_POST,true);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS,$params);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if(intval($aStatus["http_code"])==200){
        return $sContent;
    }else{
        return false;
    }
}

function microtime_float() {
    list($t1, $t2) = explode(' ', microtime());
    return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
}

function request_post($url = '', $param = '')
{
    if (empty($url) || empty($param)) {
        return false;
    }

    $postUrl = $url;
    $curlPost = $param;
    // 初始化curl
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $postUrl);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    // post提交方式
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    // 运行curl
    $data = curl_exec($curl);
    curl_close($curl);

    return $data;
}


//dec加密
function encrypt($str, $key){
    $block = mcrypt_get_block_size('des', 'ecb');
    $pad = $block - (strlen($str) % $block);
    $str .= str_repeat(chr($pad), $pad);
    return base64_encode(mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB) );
}


//dec解密
function decrypt($sStr, $sKey) {
    $decrypted= mcrypt_decrypt(
        MCRYPT_DES,
        $sKey,
        base64_decode($sStr),
        MCRYPT_MODE_ECB
    );

    $dec_s = strlen($decrypted);
    $padding = ord($decrypted[$dec_s-1]);
    $decrypted = substr($decrypted, 0, -$padding);
    return $decrypted;
}


function base64EncodeImage($image_file) {
    $base64_image = '';
    $image_data = file_get_contents($image_file);
    $base64_image = chunk_split(base64_encode($image_data));
    return $base64_image;
}

function xn_key($fromso = TRUE) {
	global $conf;
	return ($fromso && function_exists('xiuno_key')) ? xiuno_key() : (isset($conf['auth_key']) ? $conf['auth_key'] : '');
}

// 安全的加密 key，过期时间 100 秒，如果最后 2 位 大于 90，则
// 临时使用，一般用作数据传输和校验
function xn_safe_key() {
	global $conf, $longip, $time, $useragent;
	$key = xn_key();
	$behind = intval(substr($time, -2, 2));
	$t = $behind > 80 ? $time - 20 : ($behind < 20 ? $time - 40 : $time); // 修正范围，防止进位，有效时间窗口
	$front = substr($t, 0, -2);
	$key = md5($key.$useragent.$front);
	return $key;
}

function xn_encrypt($txt, $key = '') {
	empty($key) AND $key = xn_key();
	$encrypt = function_exists('xiuno_encrypt') ? xiuno_encrypt($txt, $key) : xxtea_encrypt($txt, $key);
	return urlencode(base64_encode($encrypt));
}

function xn_decrypt($txt, $key = '') {
	empty($key) AND $key = xn_key();
	$encrypt = base64_decode(urldecode($txt));
	$ret = function_exists('xiuno_decrypt') ? xiuno_decrypt($encrypt, $key) : xxtea_decrypt($encrypt, $key);
	return $ret;
}

if(!function_exists('xxtea_encrypt')) {
	function xxtea_long2str($v, $w) {
		$len = count($v);
		$n = ($len - 1) << 2;
		if ($w) {
			$m = $v[$len - 1];
			if (($m < $n - 3) || ($m > $n)) return FALSE;
			$n = $m;
		}
		$s = array();
		for ($i = 0; $i < $len; $i++) {
			$s[$i] = pack("V", $v[$i]);
		}
		if ($w) {
			return substr(join('', $s), 0, $n);
		}
		else {
			return join('', $s);
		}
	}
	
	function xxtea_str2long($s, $w) {
		$v = unpack("V*", $s. str_repeat("\0", (4 - strlen($s) % 4) & 3));
		$v = array_values($v);
		if ($w) {
			$v[count($v)] = strlen($s);
		}
		return $v;
	}
	
	function xxtea_int32($n) {
		while ($n >= 2147483648) $n -= 4294967296;
		while ($n <= -2147483649) $n += 4294967296;
		return (int)$n;
	}
	
	function xxtea_encrypt($str, $key) {
		if($str == '') return '';
		$v = xxtea_str2long($str, TRUE);
		$k = xxtea_str2long($key, FALSE);
		if (count($k) < 4) {
			for ($i = count($k); $i < 4; $i++) {
				$k[$i] = 0;
			}
		}
		$n = count($v) - 1;
	
		$z = $v[$n];
		$y = $v[0];
		$delta = 0x9E3779B9;
		$q = floor(6 + 52 / ($n + 1));
		$sum = 0;
		while (0 < $q--) {
			$sum = xxtea_int32($sum + $delta);
			$e = $sum >> 2 & 3;
			for ($p = 0; $p < $n; $p++) {
				$y = $v[$p + 1];
				$mx = xxtea_int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ xxtea_int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
				$z = $v[$p] = xxtea_int32($v[$p] + $mx);
			}
			$y = $v[0];
			$mx = xxtea_int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ xxtea_int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
			$z = $v[$n] = xxtea_int32($v[$n] + $mx);
		}
		return xxtea_long2str($v, FALSE);
	}
	
	function xxtea_decrypt($str, $key) {
		if($str == '') return '';
		$v = xxtea_str2long($str, FALSE);
		$k = xxtea_str2long($key, FALSE);
		if(count($k) < 4) {
			for ($i = count($k); $i < 4; $i++) {
				$k[$i] = 0;
			}
		}
		$n = count($v) - 1;
	
		$z = $v[$n];
		$y = $v[0];
		$delta = 0x9E3779B9;
		$q = floor(6 + 52 / ($n + 1));
		$sum = xxtea_int32($q * $delta);
		while ($sum != 0) {
			$e = $sum >> 2 & 3;
			for ($p = $n; $p > 0; $p--) {
				$z = $v[$p - 1];
				$mx = xxtea_int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ xxtea_int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
				$y = $v[$p] = xxtea_int32($v[$p] - $mx);
			}
			$z = $v[$n];
			$mx = xxtea_int32((($z >> 5 & 0x07ffffff) ^ $y << 2) + (($y >> 3 & 0x1fffffff) ^ $z << 4)) ^ xxtea_int32(($sum ^ $y) + ($k[$p & 3 ^ $e] ^ $z));
			$y = $v[0] = xxtea_int32($v[0] - $mx);
			$sum = xxtea_int32($sum - $delta);
		}
		return xxtea_long2str($v, TRUE);
	}
}